package com.bowlong.io;

import java.io.DataInput;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class ByteBufferInputStream extends InputStream implements DataInput {

	ByteBuffer in;

	public ByteBufferInputStream(ByteBuffer buff) {
		this.in = buff;
	}

	@Override
	public void readFully(byte[] b) throws IOException {
		in.get(b);
	}

	@Override
	public void readFully(byte[] b, int off, int len) throws IOException {
		in.get(b, off, len);
	}

	@Override
	public int skipBytes(int n) throws IOException {
		in.position(in.position() + n);
		return in.position();
	}

	@Override
	public boolean readBoolean() throws IOException {
		return in.get() != 0;
	}

	@Override
	public byte readByte() throws IOException {
		return in.get();
	}

	@Override
	public int readUnsignedByte() throws IOException {
		return in.get() & 0xFF;
	}

	@Override
	public short readShort() throws IOException {
		return in.getShort();
	}

	@Override
	public int readUnsignedShort() throws IOException {
		int ch1 = in.get();
		int ch2 = in.get();
		return (ch1 << 8) + (ch2 << 0);
	}

	@Override
	public char readChar() throws IOException {
		return in.getChar();
	}

	@Override
	public int readInt() throws IOException {
		return in.getInt();
	}

	@Override
	public long readLong() throws IOException {
		return in.getLong();
	}

	@Override
	public float readFloat() throws IOException {
		return in.getFloat();
	}

	@Override
	public double readDouble() throws IOException {
		return in.getDouble();
	}

	@Override
	public String readLine() throws IOException {
		throw new IOException("NoSuchMethodException");
	}

	@Override
	public String readUTF() throws IOException {
		int len = in.getInt();
		byte[] bs = new byte[len];
		in.get(bs);
		return new String(bs, "UTF-8");
	}

	@Override
	public int read() throws IOException {
		return in.get();
	}

	public int postion() {
		return in.position();
	}

	public void postion(int pos) {
		in.position(pos);
	}

	@Override
	public int available() throws IOException {
		return in.limit() - in.position();
	}

	@Override
	public void close() throws IOException {
		in.clear();
	}

	int mark;

	@Override
	public synchronized void mark(int readlimit) {
		mark = in.position();
	}

	@Override
	public synchronized void reset() throws IOException {
		in.position(mark);
	}

	@Override
	public boolean markSupported() {
		return true;
	}
}
